package com.gxa.xiaoucomeshome.controller;

import com.gxa.xiaoucomeshome.annotations.NeedToken;
import com.gxa.xiaoucomeshome.exception.BusinessException;
import com.gxa.xiaoucomeshome.exception.ExceptionCode;
import com.gxa.xiaoucomeshome.pojo.Agree;
import com.gxa.xiaoucomeshome.pojo.Order;
import com.gxa.xiaoucomeshome.service.UserService;
import com.gxa.xiaoucomeshome.pojo.User;
import com.gxa.xiaoucomeshome.service.SiteService;
import com.gxa.xiaoucomeshome.utils.FormatTool;
import com.gxa.xiaoucomeshome.utils.JsonResult;
import com.gxa.xiaoucomeshome.utils.PasswordUtils;
import com.gxa.xiaoucomeshome.utils.SnowflakeIdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 控制器的设计要点
 * 1.spring能找到并访问bean
 * 2.设置请求映射规则:通过@RequestMapping注解
 *      前端发起:localhost:8080/user/register
 *      第一个分割线后的:/user用于映射到类
 *      第二个分割线后的:/register用于映射到方法
 * @author 9
 */
@Api(value = "UserController",tags="用户模块user相关的api接口")
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    SiteService storesService;

    @ApiOperation(value = "注册的方法",produces = "body")
    @ApiImplicitParams({
            @ApiImplicitParam( name = "name",value = "用户姓名",paramType = "String",dataType = "query"),
            @ApiImplicitParam( name = "phone",value = "用户手机号",paramType = "String",dataType = "query"),
            @ApiImplicitParam( name = "pwd",value = "用户密码",paramType = "String",dataType = "query"),
    })
    @PostMapping(value="/register")
    public Map register(String name,String phone,String pwd,@ApiIgnore HttpSession session,Integer agreeState) throws BusinessException {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("token",token);

        if (userService.selectByPhone(phone)!=null){
            throw new BusinessException(ExceptionCode.DUPLICATE_PHONE);
        }
        PasswordUtils passwordUtils = new PasswordUtils();
        String s = passwordUtils.passwordUtils(pwd);
        JsonResult jsonResult =new JsonResult();
        if (agreeState==1){
            userService.insert(name,phone,s);
            jsonResult.setCode("200");
            jsonResult.setMsg("注册成功");
            jsonResult.set("token",token);
        }else {
            jsonResult.setMsg("请勾选用户协议");
        }
        return jsonResult.getMap();
    }
    /**
     * 使用路径信息传递方法
     * 路径中 表示一个变量被注入用{id}
     * 接受该变量需要用@PathVariable("id")
     * id属性要和{id}保持一致
     */
    @ApiOperation(value = "根据id查询用户信息的方法")
    @ApiImplicitParams({
            @ApiImplicitParam(name="token",value="用户token",paramType = "header")
    })
    @PostMapping(value = "selectById")
    public Map selectById(@RequestParam Integer id,
                          @RequestHeader("token") String token,
                          @ApiIgnore HttpSession session) throws Exception {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("查询成功");
        return jsonResult.getMap();
    }

    @ApiOperation(value = "修改用户信息方法")
    @ApiImplicitParams({
            @ApiImplicitParam(name="user",value="修改用户的信息",paramType = "body")
    })
    @PostMapping(value = "update")
    @NeedToken
    public Map update(@RequestHeader("token") String token,@ApiIgnore HttpSession session){
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        return jsonResult.getMap();
    }
    /**
     * 用户登录的接口
     * @phone 用户手机号
     * @pwd 用户密码
     */
    @ApiOperation(value = "登录的方法",produces = "query")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone",value = "手机号",paramType = "query"),
            @ApiImplicitParam(name = "pwd",value = "用户密码",paramType = "query")
    })
    @PostMapping(value = "/login")
    public Map login(String phone, String pwd, @ApiIgnore HttpSession session) throws BusinessException {

        String token = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("token",token);

        JsonResult jsonResult = new JsonResult();
        if(StringUtils.isEmpty(phone)){
            throw new BusinessException(ExceptionCode.USER_NOT_FOUND);
        }
        User user = userService.selectByPhone(phone);
        String pwd1 = user.getPwd();
        PasswordUtils passwordUtils = new PasswordUtils();
        String passwordUtil = passwordUtils.passwordUtils(pwd);
        if (pwd1.equals(passwordUtil)){
            jsonResult.setCode("200");
            jsonResult.setMsg("登录成功");
            jsonResult.set("token",token);
            jsonResult.set("u_id",user.getId());
            jsonResult.set("name",user.getName());
            jsonResult.set("phone",user.getPhone());
            return jsonResult.getMap();
        }
        throw new BusinessException(ExceptionCode.USER_FAILED);
    }

    @ApiOperation("统计等待配送的订单数量")
    @PostMapping("/selectStateByWait")
    @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "query")
    public Map selectStateByWait(Integer uid){
        Integer integer = userService.selectStateByWait(uid);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.set("count",integer);
        return jsonResult.getMap();
    }
    @ApiOperation("统计配送中订单数量")
    @PostMapping("/selectStateByRunning")
    @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "query")
    public Map selectStateByRunning(Integer uid){
        Integer integer = userService.selectStateByRunning(uid);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.set("count",integer);
        return jsonResult.getMap();
    }
    @ApiOperation("统计配送成功订单的数量")
    @PostMapping("/selectStateBySuccess")
    @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "query")
    public Map selectStateBySuccess(Integer uid){
        Integer integer = userService.selectStateBySuccess(uid);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.set("count",integer);
        return jsonResult.getMap();
    }
    @ApiOperation("统计配送失败订单的数量")
    @PostMapping("/selectStateByFalse")
    @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "query")
    public Map selectStateByFalse(Integer uid){
        Integer integer = userService.selectStateByFalse(uid);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.set("count",integer);
        return jsonResult.getMap();
    }
    @ApiOperation("查询用户待配送订单列表")
    @PostMapping("/selectOrderListByWait")
    @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "query")
    public Map selectOrderListByWait(Integer uid){
        List<Map<String,Object>> maps = userService.selectOrderListByWait(uid);
        FormatTool formatTool = new FormatTool();
        for (Map<String, Object> map : maps) {
            formatTool.dateFormat(map,"conftime");
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(maps);
        return jsonResult.getMap();
    }
    @ApiOperation("查询用户配送中订单列表")
    @PostMapping("/selectOrderListByRunning")
    @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "query")
    public Map selectOrderListByRunning(Integer uid){
        List<Map<String,Object>> maps = userService.selectOrderListByRunning(uid);
        FormatTool formatTool = new FormatTool();
        for (Map<String, Object> map : maps) {
            formatTool.dateFormat(map,"dispatch_time");
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(maps);
        return jsonResult.getMap();
    }

    @ApiOperation("查询用户配送成功订单列表")
    @PostMapping("/selectOrderListBySuccess")
    @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "query")
    public Map selectOrderListBySuccess(Integer uid){
        List<Map<String,Object>> maps = userService.selectOrderListBySuccess(uid);
        FormatTool formatTool = new FormatTool();
        for (Map<String, Object> map : maps) {
            formatTool.dateFormat(map,"signin_time");
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(maps);
        return jsonResult.getMap();
    }
    @ApiOperation("查询用户配送失败订单列表")
    @PostMapping("/selectOrderListByFalse")
    @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "query")
    public Map selectOrderListByFalse(Integer uid){
        List<Map<String,Object>> maps = userService.selectOrderListByFalse(uid);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(maps);
        return jsonResult.getMap();
    }
    @ApiOperation("根据订单编号查询订单详情")
    @PostMapping("/selectByOrder_id")
    @ApiImplicitParam(name = "order_id",value = "订单编号",paramType = "query")
    public Map selectByOrder_id(String order_id){
        Map<String, Object> map = userService.selectByOrder_id(order_id);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getMap();
    }
    @ApiOperation("我的申请")
    @PostMapping("/selectAllOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "query"),
            @ApiImplicitParam(name = "startTime",value = "起始时间",paramType = "query"),
            @ApiImplicitParam(name = "endTime",value = "结束时间",paramType = "query"),
            @ApiImplicitParam(name = "code",value = "状态码",paramType = "query")
    })
    public Map selectAllOrder(Integer uid,String startTime,String endTime,Integer code){
        List<Map<String, Object>> maps = userService.selectAllOrder(uid,startTime,endTime,code);
        FormatTool formatTool = new FormatTool();
        for (Map<String, Object> map : maps) {
            formatTool.dateFormat(map,"order_time");
            formatTool.dateFormat(map,"confTime");
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(maps);
        return jsonResult.getMap();
    }
    @ApiOperation(value = "下单的方法",produces = "query")
    @ApiImplicitParams({
            @ApiImplicitParam( name = "site_id",value = "站点编号",paramType = "int",dataType = "query"),
            @ApiImplicitParam( name = "address_id",value = "地址编号",paramType = "int",dataType = "query"),

    })
    @PostMapping(value="/addOrder")
    public Map addOrder(Integer site_id, Integer address_id, Integer u_id,String img1,String img2){
       // String order_id = UUID.randomUUID().toString().replaceAll("-", "");
        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(0,0);
        Long l = snowflakeIdWorker.nextId();
        String order_id = l.toString();

        userService.insertOrder( order_id,site_id,address_id,(Integer) u_id,new Date(),img1,img2 );
        JsonResult jsonResult =new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("下单成功");
        return jsonResult.getMap();
    }

    @ApiOperation(value = "查询单条订单记录",produces = "query")
    @ApiImplicitParams({
            @ApiImplicitParam( name = "order_id",value = "订单编号",paramType = "String",dataType = "query"),
    })
    @PostMapping(value="/selectOrderById")
    public Map addOrder(String order_id){
        List<Map<String, Object>> maps = userService.selectOrderById(order_id);
        JsonResult jsonResult =new JsonResult();
        FormatTool formatTool = new FormatTool();
        for (Map<String, Object> map : maps) {
            formatTool.dateFormat(map,"order_time");
            formatTool.dateFormat(map,"confTime");
            formatTool.dateFormat(map,"barcode_date");
        }
        jsonResult.setData(maps);
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }

    @PostMapping(value="/selectAgree")
    @ApiOperation(value = "查询用户协议")
    public Map selectAgree(){
        List<Agree> maps = userService.selectAgree();
        JsonResult jsonResult =new JsonResult();
        jsonResult.setData(maps);
        jsonResult.setCode("200");
        return jsonResult.getMap();
    }
    @PostMapping(value="/selectByOrderState")
    @ApiOperation(value = "判断用户是否有订单在待审核状态")
    @ApiImplicitParam(name = "uid",value = "用户编号",paramType = "int",dataType = "query")
    public Map selectByOrderSate(Integer uid){
        Order order = userService.selectByOrder_state(uid);
        JsonResult jsonResult =new JsonResult();
        if (order!=null){
            Integer oListId = order.getListId();
            jsonResult.set("listId",oListId);
            jsonResult.setCode("200");
        }else {
            jsonResult.setMsg("当前没有待审核订单");
        }
        return jsonResult.getMap();
    }
}
